// pages/cate/add/index.js
import { tips, confirm, coludRequest } from '../../util/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    id:'',
    note: '',
    content: '',
    cid: '',     //当前分类ID
    cateList: [], //分类数组  
    index: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({id:options.id});
    this.getCate();
    this.getArticle(options.id);    
  },

  getTitle: function (e) {
    var val = e.detail.value;
    this.setData({ title: val });
  },

  getNote: function (e) {
    var val = e.detail.value;
    this.setData({ note: val });
  },

  getContent: function (e) {
    var val = e.detail.value;
    this.setData({ content: val });
  },

  //查询分类
  getCate: function () {
    var that = this;
    coludRequest('admin', { module: 'cate', action: 'query', map: {} }, function (res) {
      var arr = res.result.data;
      if (arr.length > 0) {
        that.setData({ cateList: res.result.data });
      }
    })
  },

  //查询文章
  getArticle: function (id) {
    var that = this;
    coludRequest('admin', { module: 'article', action: 'query', map: {_id:id} }, function (res) {
      var arr = res.result.data;
      if (arr.length > 0) {
        that.data.cateList.forEach((item,index)=>{
          if (item._id == arr[0].cid){ 
            that.setData({index:index}); 
          }
        })
        that.setData({ 
            title: arr[0].title,
            cid: arr[0].cid, 
            note: arr[0].note, 
            content: arr[0].content,  
        });
      }
    })
  },

  //选择分类
  selectCate(e) {
    var index = e.detail.value;
    this.setData({ index: index, cid: this.data.cateList[index]._id })
  },

  submitAdd: function () {
    if (this.data.title == "") {
      tips('请输入标题');
      return false;
    }
    if (this.data.cid == "") {
      tips('请选择分类');
      return false;
    }
    if (this.data.content == "") {
      tips('请输入内容');
      return false;
    }
    let params = {
      title: this.data.title,
      cid: this.data.cid,
      note: this.data.note,
      content: this.data.content
    }
    coludRequest('admin', { module: 'article', action: 'update', id:this.data.id, params: params }, function (res) {
      tips('文章编辑成功')
      setTimeout(res => {
        wx.navigateTo({
          url: '/pages/article/index',
        })
      }, 1200)
    })
  }

})